package com.zhoug.map2.location;

import android.content.Intent;
import android.location.LocationManager;
import android.provider.Settings;

import com.zhoug.map2.Utils;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.LifecycleOwner;

/**
 * 打开GPS设置
 * @Author: zhoug
 * @Date: 2025-01-07
 * @Description:
 */
public class GpsSettingHelper {
    private ActivityResultLauncher<Intent> mLauncher;
    private OnGpsChangeListener mOnGpsChangeListener;
    private LocationManager mLocationManager;

    public GpsSettingHelper(@NonNull FragmentActivity activity) {
        mLocationManager= ContextCompat.getSystemService(activity,LocationManager.class);
        mLauncher = activity.registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        if (result != null) {
                            if (mOnGpsChangeListener != null) {
                                mOnGpsChangeListener.onGpsChange(isGpsOpen());
                            }
                        }
                    }
                }
        );
        activity.getLifecycle().addObserver(new DefaultLifecycleObserver() {
            @Override
            public void onDestroy(@NonNull LifecycleOwner owner) {
                mLauncher.unregister();
            }
        });

        activity.getLifecycle().addObserver(new DefaultLifecycleObserver() {
            @Override
            public void onDestroy(@NonNull LifecycleOwner owner) {
                mLauncher.unregister();
                mOnGpsChangeListener=null;
                mLocationManager=null;
            }
        });
    }

    public boolean isGpsOpen() {
        return Utils.isGpsOpen(mLocationManager);
    }


    /**
     * gps开关状态监听器
     *
     * @param onGpsChangeListener
     */
    public void setOnGpsChangeListener(OnGpsChangeListener onGpsChangeListener) {
        this.mOnGpsChangeListener = onGpsChangeListener;
    }


    public void toGpsSetting() {
        Intent gpsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        mLauncher.launch(gpsIntent);
    }


}
